package com.cmxh.shipper.controller;

import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.RecognizeBusinessLicenseRequest;
import com.aliyun.ocr_api20210707.models.RecognizeBusinessLicenseResponse;
import com.aliyun.ocr_api20210707.models.RecognizeBusinessLicenseResponseBody;
import com.aliyun.oss.OSSClient;
import com.aliyun.teaopenapi.models.Config;
import com.cmxh.shipper.pojo.LicenseAuthentication;
import com.cmxh.shipper.service.LicenseAuthenticationService;
import com.cmxh.shipper.util.Code;
import com.cmxh.shipper.util.OSSUtil;
import com.cmxh.shipper.util.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/*
 *
 *营业执照认证信息表Controller
 * */
@RestController
@RequestMapping("/licenseAuthentication")
public class LicenseAuthenticationcontroller {
    @Autowired
    private LicenseAuthenticationService licenseAuthenticationService;

    @RequestMapping("/select/{eid}")
    public Result select(@PathVariable Integer eid) {
        LicenseAuthentication licenseAuthentication = licenseAuthenticationService.selectByPrimaryKey(eid);
        if (licenseAuthentication != null) {
            return new Result(Code.GET_OK, licenseAuthentication, "查询成功");
        }else {
            return new Result(Code.GET_ERR, "查询失败");
        }
    }

    @Autowired
    private OSSUtil ossUtil;

    @RequestMapping("/update")
    public Result update(MultipartFile file) throws Exception {
        // 打印上传的文件信息
        System.out.println(file);

        // 获取上传文件的原始文件名
        String originalFilename = file.getOriginalFilename();

        // 生成新的文件名，避免文件名冲突
        String newname = UUID.randomUUID().toString().substring(24) + "-" + originalFilename;

        // 创建OSS客户端实例
        OSSClient xx = new OSSClient(ossUtil.getUrl(), ossUtil.getId(), ossUtil.getMiyao());

        // 将文件上传到OSS
        xx.putObject(ossUtil.getTong(), newname, file.getInputStream());

        // 构建上传文件在OSS上的URL
        String url1 = ossUtil.getUrl();
        String[] split = url1.split("//");
        String url = split[0] + "//" + ossUtil.getTong() + "." + split[1] + "/" + newname;

        // 创建阿里云OCR识别请求
        RecognizeBusinessLicenseRequest pp = new RecognizeBusinessLicenseRequest();
        pp.setUrl(url); // 设置要识别的图片URL

        // 配置阿里云客户端
        Config config = new Config()
                .setAccessKeyId(ossUtil.getId()) // 设置AccessKey ID
                .setAccessKeySecret(ossUtil.getMiyao()) // 设置AccessKey Secret
                .setEndpoint("ocr-api.cn-hangzhou.aliyuncs.com"); // 设置OCR服务的Endpoint

        // 创建阿里云OCR客户端实例
        Client cc = new Client(config);

        // 发送识别请求并获取响应
        RecognizeBusinessLicenseResponse ee = cc.recognizeBusinessLicense(pp);
        RecognizeBusinessLicenseResponseBody body = ee.getBody();

        // 打印响应中的请求ID、状态码、数据和消息
        System.out.println(body.getRequestId());
        System.out.println(body.getCode());
        System.out.println(body.getData());
        System.out.println(body.getMessage());

        // 使用Jackson ObjectMapper将响应数据解析为Map
        ObjectMapper oo = new ObjectMapper();
        Map map = oo.readValue(body.getData(), Map.class);
        System.out.println(map);

        // 解析OCR识别结果
        Map data = (Map) map.get("data");
        System.out.println(data);

        LicenseAuthentication licenseAuthentication = new LicenseAuthentication();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
        Date date=formatter.parse(data.get("issueDate").toString());

        licenseAuthentication.setEnterpriseName(data.get("companyName").toString());
        licenseAuthentication.setCreditCode(data.get("creditCode").toString());
        licenseAuthentication.setLegalRepresentative(data.get("legalPerson").toString());
        licenseAuthentication.setBusinessStartDate(date);
        licenseAuthentication.setLicenseImagePath(url);
        return new Result(Code.UPDATE_OK,licenseAuthentication, "上传成功");
    }

    @RequestMapping("/add")
    public Result add(@RequestBody LicenseAuthentication licenseAuthentication) {
        System.out.println(licenseAuthentication);
        int insert = licenseAuthenticationService.insertall(licenseAuthentication);
        if (insert > 0) {
            return new Result(Code.SAVE_OK, "添加成功");
        } else {
            return new Result(Code.SAVE_ERR, "添加失败");
        }
    }


}